<template>
  <view class="index">
    <view>
      <van-cell-group>
        <van-field
          :value="carInfo"
          title-width="7.2em"
          label="车源信息"
          placeholder="请选择车源信息"
          border="true"
          readonly="true"
          is-link="true"
          label-class="label-font"
          input-class="input-font"
          @tap="selectCar"
        ></van-field>
        <van-field
          :value="`（${form.cover.length}/1）`"
          title-width="7.2em"
          input-align="right"
          label="车辆封面照"
          placeholder="请上传车辆封面照"
          border="true"
          readonly="true"
          is-link="true"
          label-class="label-font"
          input-class="input-font"
          @tap="toUploadCover"
        ></van-field>
        <van-field
          :value="form.imgs.length > 0 ? `已上传${form.imgs.length}张` : ''"
          title-width="7.2em"
          label="车辆照片(选填)"
          placeholder="请上传车辆照片"
          border="true"
          readonly="true"
          is-link="true"
          label-class="label-font"
          input-class="input-font"
          @tap="toUpload"
        ></van-field>
        <van-field
          :value="form.car_guide_price"
          title-width="7.2em"
          label="指导价（万）"
          border="true"
          readonly="true"
          placeholder="请输入指导价"
          label-class="label-font"
          input-class="input-font"
        />
        <van-field
          :value="form.price"
          title-width="7.2em"
          label="报价（万）"
          border="true"
          placeholder="请输入报价"
          label-class="label-font"
          input-class="input-font"
          @change="val => formChange({ price: val.detail })"
        />
        <van-cell title="新车">
          <van-switch
            :checked="checked"
            slot="right-icon"
            size="110"
            @change="onChangeSwitch"
          />
        </van-cell>
        <view v-show="!checked">
          <van-field
            :value="form.mileage"
            title-width="7.2em"
            label="里程数(万公里)"
            border="true"
            placeholder="请输入里程数"
            @change="val => formChange({ mileage: val.detail })"
          />
          <van-field
            :value="form.license_plate_time"
            title-width="7.2em"
            label="上牌日期"
            placeholder="请选择上牌日期"
            border="true"
            readonly="true"
            is-link="true"
            @tap="showUpTime = true"
          ></van-field>
          <van-popup :show="showUpTime" position="bottom">
            <van-datetime-picker
              type="date"
              :value="currentDate"
              :min-date="minDate"
              :max-date="maxDate"
              @cancel="showUpTime = false"
              @confirm="onConfirmUp"
            />
          </van-popup>
          <van-field
            :value="form.license_plat_address"
            title-width="7.2em"
            label="车牌所在地"
            placeholder="请选择车牌所在地"
            border="true"
            readonly="true"
            is-link="true"
            @tap="showAreaForm"
          ></van-field>
          <van-popup :show="showArea" position="bottom" get-container="body">
            <van-area
              title="省市选择"
              value="110000"
              :area-list="areaList"
              :columns-num="2"
              @confirm="onConfirm"
              @cancel="showArea = false"
            />
          </van-popup>
          <van-field
            :value="form.transfer_num"
            title-width="7.2em"
            label="过户次数"
            border="true"
            placeholder="请输入过户次数"
            @change="val => formChange({ transfer_num: val.detail })"
          />
        </view>
        <van-field
          :value="form.appearance"
          title-width="7.2em"
          label="颜色"
          border="true"
          placeholder="请输入颜色"
          label-class="label-font"
          input-class="input-font"
          @change="val => formChange({ appearance: val.detail })"
        />
        <van-field
          :value="form.production_date"
          title-width="7.2em"
          label="出厂日期"
          placeholder="请选择出厂日期"
          border="true"
          readonly="true"
          is-link="true"
          label-class="label-font"
          input-class="input-font"
          @tap="showFindTime = true"
        ></van-field>
        <van-popup :show="showFindTime" position="bottom">
          <van-datetime-picker
            type="year-month"
            :value="currentDate"
            :min-date="minDate"
            :max-date="maxDateLeave"
            title="选择年月"
            @cancel="showFindTime = false"
            @confirm="onConfirmTime"
          />
        </van-popup>
        <van-field
          :value="form.emission_name"
          title-width="7.2em"
          label="排放标准"
          placeholder="请选择排放标准"
          border="true"
          readonly="true"
          is-link="true"
          label-class="label-font"
          input-class="input-font"
          @tap="showStandard = true"
        ></van-field>
        <van-action-sheet
          :show="showStandard"
          :actions="standardActions"
          cancel-text="取消"
          @cancel="showStandard = false"
          @select="onSelectStandard"
        />
        <van-field
          :value="car_address"
          title-width="7.2em"
          label="库位"
          placeholder="请选择库位"
          border="true"
          readonly="true"
          is-link="true"
          label-class="label-font"
          input-class="input-font"
          @tap="() => toMultiArea('car_area')"
        ></van-field>
        <van-field
          :value="sale_area"
          title-width="7.2em"
          label="销售区域"
          placeholder="请选择销售区域"
          border="true"
          readonly="true"
          is-link="true"
          label-class="label-font"
          input-class="input-font"
          @tap="() => toMultiArea('sales_area')"
        ></van-field>
        <text class="remark">配置（选填）</text>
        <van-field
          :value="form.feature_desc"
          placeholder="请输入车辆描述"
          :border="false"
          type="textarea"
          :multiple="true"
          :autosize="{ minHeight: 80 }"
          label-class="label-font"
          input-class="input-font"
          @change="val => formChange({ feature_desc: val.detail })"
        />
      </van-cell-group>
      <view class="height"></view>

      <van-cell-group>
        <van-field
          :value="form.publish_expire_name"
          title-width="7.2em"
          label="寻车有效期"
          placeholder="请选择寻车有效期"
          border="true"
          readonly="true"
          is-link="true"
          label-class="label-font"
          input-class="input-font"
          @tap="showFindStatus = true"
        />
        <van-action-sheet
          :show="showFindStatus"
          :actions="actions"
          cancel-text="取消"
          @cancel="showFindStatus = false"
          @select="onSelect"
        />
        <text class="remark">标签</text>
        <view class="selected-box">
          <view>
            <view
              v-for="item in tagList"
              :key="item.value"
              :class="{ active: checkedTags.includes(item.value, item.name) }"
              @tap="() => selectTag(item)"
            >
              <text>{{ item.name }}</text>
            </view>
          </view>
        </view>
        <van-field
          :value="form.contact_name"
          title-width="7.2em"
          border="true"
          label="联系姓名"
          placeholder="请输入联系姓名"
          label-class="label-font"
          input-class="input-font"
          @change="val => formChange({ contact_name: val.detail })"
        />
        <van-field
          :value="form.contact_mobile"
          title-width="7.2em"
          label="联系方式"
          placeholder="请输入联系方式"
          label-class="label-font"
          input-class="input-font"
          @change="val => formChange({ contact_mobile: val.detail })"
        />
      </van-cell-group>
    </view>
    <view class="fix-btn">
      <van-button
        size="large"
        type="primary"
        block
        color="#006CFF;"
        @click="publish"
      >
        发布
      </van-button>
    </view>
  </view>
</template>

<script>
import request from '@utils/ajax.js'
import { publishResource } from '@requests/business'
import Taro from '@tarojs/taro'
import {
  navigateTo,
  formatter,
  goBack,
  toast,
  formatterYearMonth,
  getMaxDate,
  getMinDate
} from '@utils/index'

const rules = {
  car: '车源信息',
  color: '颜色'
}
export default {
  name: 'PublishResource',
  data() {
    return {
      carModel: null,
      checkedTags: [],
      checked: true,
      form: {
        cover: [],
        imgs: [],
        car_address: [],
        sale_area: [],
        car_type: 1,
        tag: [],
        car_area: [],
        sales_area: [],
        contact_name: this.$store.state.user.userInfo.name,
        contact_mobile: this.$store.state.user.userInfo.mobile.toString()
      },
      checkedTag: null,
      fileList: [],
      showArea: false,
      regionStr: '',
      areaList: [],
      showFindTime: false,
      showUpTime: false,
      showFindStatus: false,
      showStandard: false,
      currentDate: new Date().getTime(),
      minDate: getMinDate().getTime(),
      maxDate: getMaxDate().getTime(),
      maxDateLeave: new Date().getTime()
    }
  },
  created() {
    Taro.eventCenter.on('selectResoureCar', data => {
      this.carModel = data
      this.formChange({ car_guide_price: data.car_guide_price })
    })
    Taro.eventCenter.on('selectImg', data => {
      this.formChange({ [data.field]: data.imgs })
    })
    Taro.eventCenter.on('selectArea', data => {
      this.formChange({ [data.field]: data.data })
    })
  },
  components: {},
  computed: {
    car_address() {
      return (
        this.form.car_area &&
        this.form.car_area
          .map(item => {
            if (
              ['110000', '120000', '310000', '500000'].includes(
                `${item.pid}`
              ) ||
              !item.value
            ) {
              return item.pname
            }
            return item.label
          })
          .join('、')
      )
    },
    sale_area() {
      return (
        this.form.sales_area &&
        this.form.sales_area
          .map(item => {
            if (item.children) {
              return item.label
            }
            return item.pname + item.label
          })
          .join('、')
      )
    },
    carInfo() {
      if (!this.carModel) {
        return ''
      }
      const { car_brand_name, car_series_name, car_model_name } = this.carModel
      return `${car_brand_name} ${car_series_name} ${car_model_name}`
    },
    tagList() {
      return this.$store.state.dict.carshop_car_source_tags
    },
    actions() {
      return this.$store.state.dict.carshop_car_source_expire.map(i => {
        return {
          ...i,
          color: '#006CFF'
        }
      })
    },
    standardActions() {
      return this.$store.state.dict.look_car_emission.map(i => {
        return {
          ...i,
          color: '#006CFF'
        }
      })
    }
  },
  methods: {
    onChangeSwitch({ detail }) {
      this.checked = detail
      this.checked ? (this.form.car_type = 1) : (this.form.car_type = 2)
    },
    toMultiArea(field) {
      navigateTo('multiple-area', {
        field
      })
    },
    getAreas() {
      request({
        url: 'common/region'
      })
        .then(res => {
          this.areaList = this.formatList(res.result)
        })
        .catch(e => e)
    },
    formatList(list) {
      let areaList = { province_list: {}, city_list: {}, county_list: {} }
      Array.isArray(list) &&
        list.forEach(province => {
          areaList.province_list[province.value] = province.label
          if (Array.isArray(province.children) && province.children.length) {
            province.children.forEach(city => {
              areaList.city_list[city.value] = city.label
              if (Array.isArray(city.children) && city.children.length) {
                city.children.forEach(county => {
                  areaList.county_list[county.value] = county.label
                })
              }
            })
          }
        })
      return areaList
    },
    onConfirm(e) {
      let values = e.detail.values
      this.form.license_plat_address = values.map(item => item.name).join('/')
      this.region = {
        license_plat_province_code: values[0].code,
        license_plat_city_code: values[1].code
      }
      this.showArea = false
    },
    showAreaForm() {
      this.getAreas()
      this.showArea = true
    },
    formChange(data) {
      this.form = { ...this.form, ...data }
    },
    selectCar() {
      navigateTo('business/car-lib/index', {
        event: 'selectResoureCar'
      })
    },
    toUpload() {
      navigateTo('upload-file', {
        field: 'imgs',
        title: '车辆照片',
        max: 9,
        imgs: JSON.stringify(this.form.imgs)
      })
    },
    toUploadCover() {
      navigateTo('upload-file', {
        field: 'cover',
        title: '车辆封面照',
        imgs: JSON.stringify(this.form.cover)
      })
    },
    onSelect(e) {
      this.form.publish_expire_name = e.detail.name
      this.form.publish_expire = e.detail.value
      this.showFindStatus = false
    },
    onSelectStandard(e) {
      this.form.emission = e.detail.value
      this.form.emission_name = e.detail.name
      this.showStandard = false
    },
    publish() {
      const form = { ...this.form }
      form.car_address = this.form.car_area.map(item => {
        return {
          province_code: item.pid,
          province_name: item.pname,
          city_code: item.value,
          city_name: item.label
        }
      })
      if (
        this.form.sales_area.length === 1 &&
        this.form.sales_area[0].value === '100000'
      ) {
        form.sale_area = []
      } else {
        form.sale_area = this.form.sales_area.map(item => {
          if (item.children) {
            return {
              province_code: item.value,
              province_name: item.label
            }
          }
          return {
            province_code: item.pid,
            province_name: item.pname,
            city_code: item.value,
            city_name: item.label
          }
        })
      }
      form.imgs = this.form.cover.concat(this.form.imgs)
      form.cover_img = this.form.cover.join('')
      form.tag = this.tagList
        .filter(item => this.checkedTags.includes(item.value))
        .map(i => {
          return {
            id: i.value,
            value: i.name
          }
        })
      publishResource({
        ...form,
        ...this.carModel,
        ...this.region
      }).then(res => {
        toast.success('发布成功').then(() => {
          Taro.eventCenter.trigger('publish')
          goBack()
        })
      })
    },
    onConfirmTime(e) {
      this.form.production_date = formatterYearMonth(e.detail)
      this.showFindTime = false
    },
    onConfirmUp(e) {
      this.form.license_plate_time = formatter(e.detail)
      this.showUpTime = false
    },
    selectTag(item) {
      if (this.checkedTags.includes(item.value)) {
        this.checkedTags.splice(this.checkedTags.indexOf(item.value), 1)
      } else {
        this.checkedTags.push(item.value)
      }
    }
  }
}
</script>

<style lang="scss">
.index {
  padding-bottom: 140px;
}
.label-font {
  font-size: 0.965rem !important;
}
.input-font {
  font-size: 0.965rem !important;
}
.selected-box {
  background: #ffffff;
  padding: 0 20px 6px;
  font-size: 0.96rem;
  & > text {
    line-height: 0.48rem;
    color: #000000;
  }
  view {
    display: flex;
    flex-wrap: wrap;
    view {
      display: inline-block;
      font-size: 0.86rem;
      width: 21%;
      text-align: center;
      padding: 8px 0;
      border: 1px solid rgba(0, 0, 0, 0.35);
      border-radius: 0.3rem;
      color: #333;
      margin: 20px 20px 0 0;
      position: relative;
    }
    .active {
      border: 1px solid #006cff;
      color: #006cff;
    }
  }
}
.fix-btn {
  padding: 3%;
  width: 94%;
  position: fixed;
  left: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 99;
}
.remark {
  display: block;
  padding: 0 1rem;
  font-size: 0.865rem;
  color: #323232;
  height: 70rpx;
  line-height: 70rpx;
}
.height {
  height: 0.8rem;
  background-color: #f8f8f8;
}
.index .van-field__label {
  color: #323232;
}
</style>
